package com.dekarrin.scraton;

import com.dekarrin.util.StringWrapper;
import com.dekarrin.util.StringPadder;

public class DialogLine extends ScriptInstruction {

	private String line;
	
	private Author author;
	
	private String[] attributes;
	
	public DialogLine(long timestamp, String line, Author author, String[] attributes) {
		super(timestamp);
		this.line = line;
		this.author = author;
		this.attributes = attributes;
	}
	
	public void setFormat(ScriptFormat f) {
		if (format != null) {
			if (format.useQuotes) {
				this.line = this.line.substring(1, this.line.length() - 1);
			}
		}
		if (f.useQuotes) {
			this.line = "\"" + this.line + "\"";
		}
		this.format = f;
	}
	
	public String toString() {
		StringBuilder builder = new StringBuilder();
		StringPadder marginPadder = new StringPadder(format.leftMarginWidth, " ");
		String clearMargin = getClearLeftMargin();
		int dialogWidth = format.scriptWidth - (format.leftMarginWidth + format.rightMarginWidth);
		if (format.speakerInMargin) {
			String padded = marginPadder.padRight(getAuthorName() + ":");
			builder.append(padded);
		} else {
			int speakerLength = (dialogWidth + (getAuthorName().length() + 1)) / 2;
			StringPadder padder = new StringPadder(speakerLength, " ");
			builder.append(clearMargin + padder.padLeft(getAuthorName() + ":"));
			builder.append("\n");
			if (attributes != null) {
				String atts = getAttributes();
				int attLength = (dialogWidth + atts.length()) / 2;
				StringPadder attPadder = new StringPadder(attLength, " ");
				builder.append(clearMargin + attPadder.padLeft(atts));
				builder.append("\n");
			}
			builder.append(clearMargin);
		}
		StringWrapper wrapper = new StringWrapper(dialogWidth, "\n" + clearMargin);
		String dialog = getDialog();
		builder.append(wrapper.wrap(dialog));
		return builder.toString() + "\n\n";
	}
	
	private String getAuthorName() {
		String name = null;
		switch (format.authorLength) {
			case INITIALS:
			name = author.getInitials();
			break;
			
			case FIRST_NAME_LAST_INITIAL:
			name = author.getFirstNameLastInitial();
			break;
			
			case FIRST_INITIAL_LAST_NAME:
			name = author.getFirstInitialLastName();
			break;
			
			case SHORT_NAME:
			name = author.getShortName();
			break;
			
			case FULL_NAME:
			name = author.getFullName();
			break;
		}
		return name.toUpperCase();
	}

	private String getDialog() {
		String dialog = "";
		if (format.speakerInMargin) {
			dialog += getAttributes();
		}
		dialog += line;
		return dialog;
	}
	
	private String getAttributes() {
		String atts = "";
		if (attributes != null) {
			atts = "(";
			for (int i = 0; i < attributes.length; i++) {
				atts += attributes[i];
				if (i + 1 < attributes.length) {
					atts += ", ";
				}
			}
			atts += ")";
			if (format.speakerInMargin) {
				atts += " ";
			}
		}
		return atts;
	}
}